// pages/WcardRecharge/WcardRecharge.js
var app = getApp();
var util = require("../../../utils/util.js");


Page({

  /**
   * 页面的初始数据
   */
  data: {
    modal: false,
    modalContent: "",
    card_number: '',
    priceList: [],
    giveList: [],
    state: '',
    money: 0,
    give: 0,
    balance: 0,
    account_recharge_balance: 0,
    is_input: false,
    template_id: '',
    other_money: '',
    promationList: [],
    cardInfo: "", //水卡获取到的相关数据
    templateList: [], //模板列表
    template_index: '', //选中的模板下标
    custom: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getPartnerQuota();
    this.getTemplateList();
  },





  //获取充值模板
  getTemplateList() {
    var that = this;
    app.ajax({
      url: 'Partner/Village/templateList',
      method: "POST",
      data: {
        row: 100,
        template_species: 3
      },
      success: function (res) {
        var flag = res.data;
        if (flag.code < 0) {
          app.showToast(flag.message);
          return false;
        }
        var template_index = '';
        const templates = res.data.data.data;
        let priceList = [],
          giveList = [],
          template_id = "";
        templates.forEach((item, index) => {
          if (item.is_default == 1) {
            template_index = index;
            template_id = item.id;
            const temps = Object.values(item.template);
            temps.forEach(current => {
              priceList.push(current.recharge);
              giveList.push(current.give);
            })
          }
        })
        that.setData({
          priceList,
          giveList,
          template_id,
          templateList: templates,
          template_index: template_index
        });
      }
    })
  },

  //切换充值模板
  templateChange(e) {
    var value = e.detail.value;
    if (this.data.template_index == value) {
      return false;
    }
    var template_data = this.data.templateList[value].template;
    const temps = Object.values(template_data);
    let priceList = [],
      giveList = [];
    temps.forEach(current => {
      priceList.push(current.recharge);
      giveList.push(current.give);
    })
    this.setData({
      money: 0,
      give: 0,
      is_input: false,
      other_money: '',
      template_index: value,
      state: '', //置空选中的金额
      priceList,
      giveList,
      template_id: this.data.templateList[value].id
    })

  },


  chooseVillageItem(e) {
    const index = e.currentTarget.dataset.index;
    const list = this.data.promationList;
    list[index].checked = !list[index].checked;
    this.setData({
      promationList: list
    })
  },

  //根据园区id来获取促销活动
  getPromotionByVillage(village_id) {
    app.ajax({
      url: "Partner/Promotion/getPromotionListByVillage",
      data: {
        village_id
      },
      success: res => {
        if (res.data.code === 1000) {
          this.setData({
            promationList: res.data.data
          })
        }
      },
      error: () => {
        app.showToast("获取园区促销活动失败");
        return;
      }
    })
  },

  // 水卡号
  card_number: function (e) {
    const val = e.detail.value;
    if (val == "") {
      this.setData({
        cardInfo: ""
      })
    }
    this.setData({
      card_number: app.formatCard(val)
    })
  },
  find_card: function (e) {
    var that = this;
    const card_number = app.trimAll(e.detail.value);
    if (card_number == '') {
      app.showToast('请输入卡号');
      return
    }
    app.ajax({
      url: 'Partner/WaterCard/getWaterCard',
      method: "POST",
      data: {
        card: card_number
      },
      success: function (res) {
        var flag = res.data;
        if (flag.code < 0) {
          that.setData({
            cardInfo: "",
          })
          app.showToast(flag.message);
          return false;
        }
        console.log(flag, "flag");
        flag.data.tel = flag.data.tel ? flag.data.tel.replace(/^(\d{3})\d{4}(\d+)/, "$1****$2") : "暂无登记号码";
        that.setData({
          balance: flag.data.balance,
          cardInfo: flag.data
        });
        that.getPromotionByVillage(flag.data.rq_id);
      }
    })
  },
  // 扫码
  scan: function () {
    wx.scanCode({
      success: (res) => {
        this.setData({
          card_number: app.formatCard(res.result)
        })
        this.find_card()
      },
      fail: (res) => {
        app.showToast('请扫描正确条形码');
      }
    })
  },

  // 选择充值金额
  choosePrice: function (e) {
    var that = this;
    let index = e.currentTarget.dataset.in;
    let money = 0,
      give = 0;
    if (this.data.state === index && index != -1) {
      return false;
    } else if (index == -1) {
      this.setData({
        custom: true
      })
      money = this.data.other_money;
      give = this.data.state != -1 ? 0 : that.data.give;
    } else {
      money = parseFloat(that.data.priceList[e.currentTarget.dataset.in]);
      give = parseFloat(that.data.giveList[e.currentTarget.dataset.in]);
    }
    if (index != -1) {
      that.setData({
        is_input: false,
        other_money: ''
      });
    }
    that.setData({
      state: index,
      money,
      give
    });
  },



  price: function (e) {
    let value = e.detail.value;
    let money = app.retainDecimal(value);
    this.setData({
      other_money: money,
      money: money,
      give: 0,
      is_input: true,
      state: 'index'
    });
  },

  partnerRecharge() {
    var that = this;
    app.ajax({
      url: 'Partner/Village/partnerRecharge',
      method: "POST",
      data: {},
      success: function (res) {
        var flag = res.data;
        if (flag.code < 0) {
          app.showToast(flag.message);
          return false;
        }
        that.setData({
          priceList: [
            flag.data.template.money_1.recharge,
            flag.data.template.money_2.recharge,
            flag.data.template.money_3.recharge,
            flag.data.template.money_4.recharge,
            flag.data.template.money_5.recharge,
            flag.data.template.money_6.recharge,
            flag.data.template.money_7.recharge,
          ],
          giveList: [
            flag.data.template.money_1.give,
            flag.data.template.money_2.give,
            flag.data.template.money_3.give,
            flag.data.template.money_4.give,
            flag.data.template.money_5.give,
            flag.data.template.money_6.give,
            flag.data.template.money_7.give,
          ],
        });
        //
        if (util.isExitsVariable(flag.data.id)) {
          template_id = flag.data.id;
        }
      }
    })
  },
  getPartnerQuota() {
    var that = this;
    app.ajax({
      url: 'Partner/WaterCard/getPartnerQuota',
      method: "POST",
      data: {},
      success: function (res) {
        var flag = res.data;

        if (flag.code < 0) {
          app.showToast(flag.message);
          return false;
        }
        that.setData({
          account_recharge_balance: flag.data.account_recharge_balance
        });
      }
    })
  },
  waterCardRecharge: function (e) {
    var that = this;
    if (app.trimAll(that.data.card_number).length == 0) {
      app.showToast('请输入水卡号或者扫描水卡');
      return false;
    }
    let promotion_id = [];
    let promationList = that.data.promationList;
    if (promationList.length > 0) {
      promationList.forEach(item => {
        if (item.checked) {
          promotion_id.push(item.id)
        }
      })
    }
    console.log(that.data.money, "that.data.money ");
    if (that.data.money <= 0 && promotion_id.length == 0) {
      app.showToast('请至少选择一种类型进行充值');
      return false;
    }
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(that.data.money) || regNeg.test(that.data.money)) {

    } else {
      app.showToast('请输入正确的金额');
      return false;
    }
    that.promotion_id = promotion_id;
    that.setData({
      modal: true,
      modalContent: `确定为${that.data.cardInfo.full_name || ''}尾号【${app.trimAll(that.data.card_number).substr(-5,5)}】的水卡充值${that.data.money}元,并赠送${that.data.give || 0}元${promotion_id.length>0?"，并参与促销活动":''}。`
    })
  },



  hideModal() {
    this.setData({
      modal: false
    })
    delete(this.promotion_id)
  },

  handleClick(e) {
    const index = e.detail.index;
    if (index == 0) {
      this.hideModal()
    } else {
      let that = this;
      app.ajax({
        url: 'Partner/WaterCard/waterCardRecharge',
        method: "POST",
        data: {
          card: app.trimAll(that.data.card_number),
          money: that.data.money,
          give: that.data.give,
          template_id: that.data.is_input ? '' : that.data.template_id,
          promotion_id: this.promotion_id
        },
        success: function (res) {
          that.hideModal();
          var flag = res.data;
          if (flag.code > 0) {
            app.showToast(flag.message, "success");
            that.setData({
              other_money: '',
              money: 0,
              give: 0,
              state: '',
              card_number: '',
              is_input: false,
              cardInfo: "",
            })
            that.getPartnerQuota();
          } else {
            app.showToast(flag.message)
          }
        }
      })
    }
  },



  hideCustom() {
    this.setData({
      custom: false
    })
  },

  handleMoneyInput(e) {
    let money = app.retainDecimal(e.detail.value);
    this.setData({
      other_money: money,
      money,
      is_input: true
    })
  },

  handleInput(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: app.retainDecimal(e.detail.value)
    })
  }

})